#include<iostream>
#include<string.h>
//理解一个整体的思想
using std::endl;
using std::cout;
using std::string;

//基础类
class Monster{

public:
    //拷贝构造
    Monster(const char*name,const int&hp)
    :_name(new char[strlen(name)+1]())
    ,_hp(hp)
    {
        cout<<"Monster (const char*name,const int&hp)"<<endl;
        strcpy(_name,name);
    }
    //我要创建堆上对象
    ~Monster(){
        if(_name){
            delete [] _name;
            _name = nullptr;
        }
        cout<<"~Monster"<<endl;
    }
    
    //堆上的情况
    Monster(const Monster&rhs)
    :_name(new char[strlen(rhs._name)+1]())
    ,_hp(rhs._hp)
    {
        cout<<"Monster(const Monster&rhs)"<<endl;
    }

    Monster&operator=(const Monster&rhs){
        if(this!=&rhs){
            delete []_name;
            _name = new char[strlen(rhs._name)]();
            strcpy(_name,rhs._name);
            _hp = rhs._hp;
        }
        return *this;
    }

protected:
    char* _name;
    int _hp;
};

class chirdMonst
:public Monster
{
public:
    chirdMonst(const char*name,const int&hp,const char*species)
    :Monster(name,hp)
    ,_species(new char[strlen(species)+1]())
    {
        cout<<"chirdMonst(const char*name,const int&hp,const char*species)"<<endl;
    }
    ~chirdMonst(){
        if(_species){
            delete [] _species;
            _species = nullptr;
        }
    }
    //重新写chirdMonster的构造解决double free的问题
    chirdMonst(const chirdMonst&rhs)
    :Monster(rhs)
    ,_species(new char[strlen(rhs._species)]())
    {   
        strcpy(_species,rhs._species);
    }

    chirdMonst& operator=(const chirdMonst&rhs){
        if(this!= &rhs){
            //先调用基类
            Monster::operator=(rhs);
            delete [] _species;
            _species = new char[strlen(rhs._species)]();
            strcpy(_species,rhs._species);
        }
        return *this;
    }

private:
    //种类
    char*_species;
};


void test0(){
    //double free的情况
    chirdMonst m1("slime01",100,"slime");
    chirdMonst m2 = m1;
    chirdMonst m3("slime03",100,"slime");
    //doube free的情况
    m3 = m2;
}

int main(void){
    test0();
    return 0;
}